#
# ship.py -- ship object
# 
# author: Tom "Knio" Flanagan
#         knio@h4xn3t.net
#         theknio@gmail.com
#         irc.freenode.net - Knio - #python #pygame #py
#
# this file released under Public Domain
#


from constants import *
import object
import explosion
import scrap
import ai

class Ship(object.Object):
    def __init__(self, battle, **kwargs):
        self.weapons = []
        self.maxa = 0.01
        self.maxt = 0.1
        self.hull = 50.
        self.shld = 5.
        self.mintarg = 0
        self.maxtarg = 10
        self.target = None
        self.ai = ai.Ai(self, battle)
        object.Object.__init__(self, battle, **kwargs)

    def poll(self):
        for i in self.weapons: i.reload()
        self.ai.tick(self.data)
        
    def move(self):
        if not self.state: return object.Object.move(self)
        if (abs(self.x) > self.battle.size) or (abs(self.y) > self.battle.size):
            self.target = object.Vector(0., 0., a=self.maxa)
        if not self.target: self.target = object.Vector(0.,0.,a=0.)
        turn = self.direction(self.angle(self.target))
        if     turn > self.maxt: self.t =  self.maxt
        elif  -turn > self.maxt: self.t = -self.maxt
        else: self.t = turn

        if      self.target.a > self.maxa: self.a = self.maxa
        elif    self.target.a < 0: self.a = 0
        else:   self.a = self.target.a
        object.Object.move(self)


    def hit(self, weapon, damage):
        self.ai.hit(weapon, damage)
        if self.shld:
            if self.shld >= damage: self.shld -= damage; damage = 0
            else:                   damage -= self.shld; self.shld = 0
        if self.hull >= damage: self.hull -= damage; damage = 0
        if self.hull <= damage: damage -= self.hull; self.hull = 0
        if self.hull <= 0: self.die(damage)

    def die(self, damage):
        if not self.state: return
        n = int(math.sqrt(damage/self.size))+1
        for i in range(n):
            scrap.Scrap(self.battle, size=math.sqrt(self.size**2/float(n)), **self.coordinates(CI*(i/float(n)),2*i).vector())
        self.explode()

    def explode(self):
        self.currentsize = 0
        self.power = 1.0
        self.size *= 7
        self.view = None
        self.a = 0
        self.__class__ = explosion.Explosion


        
        
